package net.betou.trade.main.dao.impl;

import java.util.List;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.common.page.Pagination;
import net.betou.trade.entity.main.Content;
import net.betou.trade.main.dao.ContentDao;

import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;

@Repository
public class ContentDaoImpl extends HibernateBaseDao< Content, Integer > implements ContentDao{

	@Override
	protected Class< Content > getEntityClass( ) {
		return Content.class;
	}

	public Content deleteById( Integer id ) {
		Content channel = get( id );
		if( channel != null ){
			getSession( ).delete( channel );
		}
		
		return channel;
	}

	public Content findById( Integer id ) {
		return get(id);
	}

	public Content save( Content bean ) {
		getSession( ).save( bean );
		return bean;
	}
	
	public Pagination getPage( Integer selfId, String searchProperty, String searchValue, String orderProperty, String orderDirection, int pageNo, int pageSize ){
		
		Finder f = Finder.create( " from Content bean where 1=1 " );
		if( selfId != null ){
			f.append( " and bean.admin.id=:id" );
			f.setParam( "id", selfId );
		}
		createSearch( f, searchProperty, searchValue );
		createOrder( f, orderProperty, orderDirection, "id" );
		
		return find( f, pageNo, pageSize );
	}
	
	public Content findMyContent( Integer id, Integer selfId ){
		String hql = "from Content bean where bean.id=? and bean.admin.id=?";
		return ( Content ) this.findUnique( hql, id, selfId );
		
	}
	
	public Pagination getPage(   Integer groupId, List< Integer > channelIdList, int pageNo, int pageSize ){
		
		StringBuilder sqls = new StringBuilder( " 1=1 and" );
		
		sqls.append( "(" );
		for( int i = 0; i < channelIdList.size( ); i++ ){
			
			sqls.append( " channel_id=" );
			sqls.append( channelIdList.get( i ) );
			
			if( i < channelIdList.size( ) - 1 ){
				sqls.append( " or " );
			}
		}
		sqls.append( ")" );
		
		Criteria c = this.createCriteria( sqls.toString( ) ); // 创建对象
		createOrder( c, "id", "desc", "id" );
		Pagination p = this.findByCriteria( c, pageNo, pageSize );
		return p;
	}
	
}